package cn.com.checne.controller.superManager;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.checne.constants.Constants;
import cn.com.checne.controller.BaseController;
import cn.com.checne.dao.ChecNewsDao;
import cn.com.checne.dao.ContentInfoDao;
import cn.com.checne.dao.LogInfoDao;
import cn.com.checne.dao.NewsCategoryDao;
import cn.com.checne.dao.NewsInfoDao;
import cn.com.checne.dao.WebsiteInfoDao;
import cn.com.checne.model.domain.ContentInfo;
import cn.com.checne.model.domain.NewsCategory;
import cn.com.checne.model.domain.NewsInfo;
import cn.com.checne.model.domain.UserInfo;
import cn.com.checne.model.domain.WebsiteInfo;
import cn.com.checne.model.dto.NewsQuery;
import cn.com.checne.util.PageBean;
import cn.com.checne.util.StringTools;
import cn.com.checne.util.TimeUtils;
import cn.com.checne.util.WebUtils;
import cn.com.checne.util.XMLUtils;
import cn.com.checne.util.images.ImageContentUtils;

@Controller
@RequestMapping(value = "/super/news")
public class NewsInfoManagerController extends BaseController {

    protected static final Logger logger = Logger.getLogger(NewsInfoManagerController.class);
    @Resource
    private NewsCategoryDao categoryDao;
    @Resource
    private NewsInfoDao newsDao;
    @Resource
    private ChecNewsDao checNewsDao;
    @Resource
    private LogInfoDao logDao;
    
    @Resource
    private WebsiteInfoDao websiteInfoDao;
    @Resource
    private ContentInfoDao contentInfoDao;

    //新闻管理--首页
    @RequestMapping(value = "/index.do")
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        return "super/frame/frame_news";
    }

    //新闻管理--左侧导航
    @RequestMapping(value = "/left.do")
    public String left(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        return "super/news/left";
    }

    //新闻管理--列举所有的栏目
    @RequestMapping(value = "/category-list.do")
    public ModelAndView navigateList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        int languageId = (String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1;

        List<NewsCategory> categoryList = categoryDao.getAll(languageId);
        modelMap.put("categoryList", categoryList);
        modelMap.put("languageId", languageId);
        mav.setViewName("super/news/category-list");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--栏目新增、修改页面
    @RequestMapping(value = "/category-show.do")
    public ModelAndView navigateShow(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
        int languageId = (String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1;

        NewsCategory cate = new NewsCategory();
        cate.setLanguageId(languageId);
        String opt = "create";
        if (cateId > 0) {
            cate = categoryDao.getNewsCategory(cateId);
            opt = "update";
        }
        modelMap.put("cate", cate);
        modelMap.put("opt", opt);
        mav.setViewName("super/news/category-show");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--栏目新增
    @RequestMapping(value = "/category-create.do")
    public ModelAndView navigateCreate(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        NewsCategory cate = new NewsCategory();
        cate.setName(WebUtils.getRequestParameterAsString(request, "name"));
        cate.setDesc(WebUtils.getRequestParameterAsString(request, "desc"));
        cate.setOrder(WebUtils.getRequestParameterAsInt(request, "order", 0));
        cate.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId", 1));
        if (categoryDao.create(cate)) {
            message = "栏目创建成功!";
        } else {
            message = "栏目创建失败!";
        }
        modelMap.put("message", message);
        modelMap.put("href", "super/news/category-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--栏目修改
    @RequestMapping(value = "/category-update.do")
    public ModelAndView navigateUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        NewsCategory cate = new NewsCategory();
        int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
        cate = categoryDao.getNewsCategory(cateId);
        cate.setName(WebUtils.getRequestParameterAsString(request, "name"));
        cate.setDesc(WebUtils.getRequestParameterAsString(request, "desc"));
        cate.setOrder(WebUtils.getRequestParameterAsInt(request, "order", 0));
        cate.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId", 1));
        if (categoryDao.update(cate)) {
            message = "栏目修改成功!";
        } else {
            message = "栏目修改失败!";
        }
        modelMap.put("message", message);
        modelMap.put("href", "super/news/category-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--栏目删除
    @RequestMapping(value = "/category-del.do")
    public ModelAndView navigateDel(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
        if (categoryDao.delete(cateId)) {
            message = "栏目删除成功!";
        } else {
            message = "栏目删除失败!";
        }
        modelMap.put("message", message);
        modelMap.put("href", "super/news/category-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--新闻--列举所有
    @RequestMapping(value = "/news-list.do")
    public ModelAndView newsList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        int languageId = (String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1;
        List<NewsCategory> cateList = categoryDao.getAll(languageId);

        String kw = WebUtils.getRequestParameterAsString(request, "kw");
        kw = StringTools.converISO2UTF8(kw);
        int cateId = 1 ; //默认显示公司新闻
        
        String cateIdString = request.getParameter("cateId");
        //中文语种
        if(languageId == 1 && StringUtils.isBlank(cateIdString)){
        	cateId = 1 ;
        }
        //英文语种
        else if(languageId == 2 && StringUtils.isBlank(cateIdString)){
        	cateId = 5 ;
        }
        else {
        	cateId = Integer.valueOf(cateIdString);
        }
        
        int isShowIndex = WebUtils.getRequestParameterAsInt(request, "isShowIndex", -1);
        int isShowList = WebUtils.getRequestParameterAsInt(request, "isShowList", -1);
        int isTop = WebUtils.getRequestParameterAsInt(request, "isTop", -1);
        String startTime = WebUtils.getRequestParameterAsString(request, "startTime");
        String endTime = WebUtils.getRequestParameterAsString(request, "endTime");

        NewsQuery query = new NewsQuery();
        query.setKw(kw);
        query.setLanguageId(languageId);
        query.setCateId(cateId);
        query.setIsShowIndex(isShowIndex);
        query.setIsShowList(isShowList);
        query.setIsTop(isTop);
        query.setStartTime(startTime);
        query.setEndTime(endTime);
        int curPage = WebUtils.getRequestParameterAsInt(request, "curPage", 1);
        PageBean pageBean = new PageBean();
        pageBean.setCurPage(curPage);
        List<NewsInfo> newsList = newsDao.getNewsListByCondition(query, pageBean.getStart(), pageBean.getRowsPerPage());
        pageBean.setMaxRowCount(newsDao.getNewsCountByCondition(query));
        pageBean.setMaxPage();
        pageBean.setPageNoList();

        modelMap.put("cateList", cateList);
        modelMap.put("newsList", newsList);
        modelMap.put("query", query);
        modelMap.put("pageBean", pageBean);
        mav.setViewName("super/news/news-list");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--新闻新增、修改页面
    @RequestMapping(value = "/news-show.do")
    public ModelAndView newsShow(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        int newsId = WebUtils.getRequestParameterAsInt(request, "newsId", 0);
        int languageId = (String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String) request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1;
        List<NewsCategory> cateList = categoryDao.getAll(languageId);
        NewsInfo news = new NewsInfo();
        news.setLanguageId(languageId);
        String opt = "create";
        if (newsId > 0) {
            news = newsDao.getNewsById(newsId);
            String content = news.getContent();
            String replaceContent = ImageContentUtils.setBasePathToImagePath(request,content);
            news.setContent(replaceContent);
            opt = "update";
        }
        modelMap.put("cateList", cateList);
        modelMap.put("opt", opt);
        modelMap.put("news", news);
        modelMap.put("languageId", languageId);
        mav.setViewName("super/news/news-show");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--新闻新增
    @RequestMapping(value = "/news-create.do")
    public ModelAndView newsCreate(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("common/message");
        NewsInfo news = new NewsInfo();
        String content = WebUtils.getRequestParameterAsString(request, "content");
        String textContent = WebUtils.getRequestParameterAsString(request, "textContent");
        int contentType = WebUtils.getRequestParameterAsInt(request, "contentType", 1);
        if ((StringUtils.isBlank(content) && contentType == 1)  || (StringUtils.isBlank(textContent)) && contentType == 0) {
            modelMap.put("message", "内容不能为空!");
            mav.addAllObjects(modelMap);
            return mav;
        }
        news.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId", 1));
        news.setCateId(WebUtils.getRequestParameterAsInt(request, "cateId", 0));
        news.setTitle(WebUtils.getRequestParameterAsString(request, "title"));
        news.setAuthor(WebUtils.getRequestParameterAsString(request, "title"));
        news.setPublishFrom(WebUtils.getRequestParameterAsString(request, "publishFrom"));
        news.setAuthor(WebUtils.getRequestParameterAsString(request, "author"));
        String publishDate = WebUtils.getRequestParameterAsString(request, "publishDate");
        news.setPublishDate(StringUtils.isBlank(publishDate) ? new Date() : TimeUtils.formatDate(publishDate));
        news.setMetaKeyword(WebUtils.getRequestParameterAsString(request, "metaKeyword"));
        news.setMetaContent(WebUtils.getRequestParameterAsString(request, "metaContent"));
        news.setSummary(news.getMetaContent());

        if(contentType == 0 ){
        	news.setContent(textContent);
        }
        else{
        	Map<String,String> map = ImageContentUtils.removeImageBasePathForMap(request, content);
            news.setContent(map.get("content"));
            news.setFirstImage(map.get("firstImage"));
        }
        news.setContentType(contentType);
        if (newsDao.create(news)) {
            message = "新闻创建成功!";
            //重置滚动图片
            NewsQuery query = new NewsQuery();
            query.setLanguageId(1);
            //必须是公司新闻动态类别
            query.setCateId(1);
            XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "cn");

            query.setLanguageId(2);
            //必须是公司新闻动态类别
            query.setCateId(5);
            XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "en");

        } else {
            message = "新闻创建失败!";
        }
        modelMap.put("message", message);
        modelMap.put("href", "super/news/news-list.do?cateId=" + WebUtils.getRequestParameterAsInt(request, "cateId", 1));
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--新闻修改
    @RequestMapping(value = "/news-update.do")
    public ModelAndView newsUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        String content = WebUtils.getRequestParameterAsString(request, "content");
        if (StringUtils.isBlank(content)) {
            modelMap.put("message", "内容不能为空!");
            mav.addAllObjects(modelMap);
            return mav;
        }

        int newsId = WebUtils.getRequestParameterAsInt(request, "newsId", 0);
        NewsInfo news = new NewsInfo();
        news = newsDao.getNewsById(newsId);

        news.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId", 1));
        news.setCateId(WebUtils.getRequestParameterAsInt(request, "cateId", 0));
        news.setTitle(WebUtils.getRequestParameterAsString(request, "title"));
        news.setAuthor(WebUtils.getRequestParameterAsString(request, "title"));
        news.setPublishFrom(WebUtils.getRequestParameterAsString(request, "publishFrom"));
        news.setAuthor(WebUtils.getRequestParameterAsString(request, "author"));
        String publishDate = WebUtils.getRequestParameterAsString(request, "publishDate");
        news.setPublishDate(StringUtils.isBlank(publishDate) ? new Date() : TimeUtils.formatDate(publishDate));
        news.setMetaKeyword(WebUtils.getRequestParameterAsString(request, "metaKeyword"));
        news.setMetaContent(WebUtils.getRequestParameterAsString(request, "metaContent"));
        news.setSummary(news.getMetaContent());

        
        Map<String,String> map = ImageContentUtils.removeImageBasePathForMap(request, content);
        news.setContent(map.get("content"));
        news.setFirstImage(map.get("firstImage"));


        if (newsDao.update(news)) {
            message = "新闻修改成功!";
            //重置滚动图片
            NewsQuery query = new NewsQuery();
            query.setLanguageId(1);
            //必须是公司新闻动态类别
            query.setCateId(1);
            XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "cn");

            query.setLanguageId(2);
            //必须是公司新闻动态类别
            query.setCateId(5);
            XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "en");
        } else {
            message = "新闻修改失败!";
        }
        modelMap.put("message", message);
        modelMap.put("href", "super/news/news-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--新闻删除
    @RequestMapping(value = "/news-del.do")
    public ModelAndView newsDel(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        message = "新闻删除成功!";
        String newsId = WebUtils.getRequestParameterAsString(request, "newsId");
        String ids[] = StringUtils.split(newsId, ",");
        boolean flag = false;
        for (String id : ids) {
            flag = newsDao.delete(Integer.parseInt(id));
            if (flag == false) {
                message = "新闻删除失败!";
                break;
            }
        }

        //重置滚动图片
        NewsQuery query = new NewsQuery();
        query.setLanguageId(1);
        //必须是公司新闻动态类别
        query.setCateId(1);
        XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "cn");

        query.setLanguageId(2);
        //必须是公司新闻动态类别
        query.setCateId(5);
        XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "en");


        modelMap.put("message", message);
        modelMap.put("href", "super/news/news-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--首页显示设置
    @RequestMapping(value = "/news-setIndex.do")
    public ModelAndView newsSetIndex(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        String newsId = WebUtils.getRequestParameterAsString(request, "newsId");
        String flag = WebUtils.getRequestParameterAsString(request, "flag");
        if (StringUtils.isNotBlank(flag) && flag.matches("\\d+")) {
            String nds[] = StringUtils.split(newsId, ",");
            int newsIds[] = new int[nds.length];
            int i = 0;
            for (String nd : nds) {
                newsIds[i] = Integer.valueOf(nd);
                i++;
            }
            if (newsDao.setShowIndex(Integer.valueOf(flag), newsIds)) {
                message = "新闻" + (flag.equals("1") ? "设置首页显示" : "取消首页显示") + "成功!";
                
              //重置滚动图片
                NewsQuery query = new NewsQuery();
                query.setLanguageId(1);
                //必须是公司新闻动态类别
                query.setCateId(1);
                XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "cn");

                query.setLanguageId(2);
                //必须是公司新闻动态类别
                query.setCateId(5);
                XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "en");
                
                
            } else {
                message = "新闻" + (flag.equals("1") ? "设置首页显示" : "取消首页显示") + "失败!";
            }
        }

        modelMap.put("message", message);
        modelMap.put("href", "super/news/news-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //新闻管理--列表页显示设置
    @RequestMapping(value = "/news-setList.do")
    public ModelAndView newsSetList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        ModelAndView mav = new ModelAndView();
        String newsId = WebUtils.getRequestParameterAsString(request, "newsId");
        String flag = WebUtils.getRequestParameterAsString(request, "flag");
        if (StringUtils.isNotBlank(flag) && flag.matches("\\d+")) {
            String nds[] = StringUtils.split(newsId, ",");
            int newsIds[] = new int[nds.length];
            int i = 0;
            for (String nd : nds) {
                newsIds[i] = Integer.valueOf(nd);
                i++;
            }
            if (newsDao.setShowList(Integer.valueOf(flag), newsIds)) {
                message = "新闻" + (flag.equals("1") ? "设置列表页显示" : "取消列表页显示") + "成功!";
                
              //重置滚动图片
                NewsQuery query = new NewsQuery();
                query.setLanguageId(1);
                //必须是公司新闻动态类别
                query.setCateId(1);
                XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "cn");

                query.setLanguageId(2);
                //必须是公司新闻动态类别
                query.setCateId(5);
                XMLUtils.buildXML(newsDao.getNewsImagesListByCondition(query, 0, 6), "en");
                
                
            } else {
                message = "新闻" + (flag.equals("1") ? "设置列表页显示" : "取消列表页显示") + "失败!";
            }
        }

        modelMap.put("message", message);
        modelMap.put("href", "super/news/news-list.do");
        mav.setViewName("common/message");
        mav.addAllObjects(modelMap);
        return mav;
    }

    //获取chec主站的新闻信息
    @RequestMapping({"/news-checNews.do"})
    public void checNews(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
      response.setCharacterEncoding("UTF-8");
      PrintWriter out = response.getWriter();
      String yestoday = request.getParameter("date");
      String lg = request.getParameter("lg");
      if ((StringUtils.isBlank(yestoday)) || (!yestoday.matches("\\d{4}-\\d{2}-\\d{2}"))) {
        yestoday = TimeUtils.getDate(new Date(), -1);
      }
      if(StringUtils.equalsIgnoreCase(lg, "cn")){
          newsDao.checCNNewsSynch(yestoday);
      }
      else if(StringUtils.equalsIgnoreCase(lg, "en")){
        newsDao.checENNewsSynch(yestoday);
      }
      else {
          out.print("{msg:没有指定语种}");
      }
      out.print("{date:" + yestoday + ",status:ok}");
      out.flush();
      out.close();
    }
    
    @RequestMapping(value = { "/news-showNewsSynch.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView showNewsSynch(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView(
				"super/synch/content-showSynch");
		String newsIds = WebUtils
				.getRequestParameterAsString(request, "newsId");
		if (StringUtils.isBlank(newsIds)) {
			map.put("message", "请选择要同步的新闻!");
			mav.addAllObjects(map);
			mav.setViewName("common/message");
			return mav;
		}
		int websiteSelfId = 0;
		List<WebsiteInfo> websiteInfoList = websiteInfoDao.getSubList(null, 0,
				2147483647);
		for (WebsiteInfo website : websiteInfoList) {
			if (website.getIsSelf() == 1) {
				websiteSelfId = website.getId();
			}
		}

		List<ContentInfo> contentInfoList = new ArrayList<ContentInfo>();
		String[] ids = newsIds.split(",");
		NewsInfo newsInfo = null;
		ContentInfo contentInfo = new ContentInfo();
		for (String newsId : ids) {
			newsInfo = newsDao.getNewsById(Integer.valueOf(newsId).intValue());
			contentInfo.setContentId(StringTools.getUUID());
			contentInfo.setTitle(newsInfo.getTitle());
			contentInfo.setWebsiteId(websiteSelfId);
			contentInfo.setText(newsInfo.getContent());
			contentInfo.setUserId(((UserInfo) session.getAttribute("systemUserInfo")).getId());
			contentInfo.setPublishTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
			contentInfoList.add(contentInfo);
			contentInfoDao.insert(contentInfo);
		}
		map.put("websiteInfoList", websiteInfoList);
		map.put("contentInfoList", contentInfoList);
		mav.addAllObjects(map);
		return mav;
	}
}